<?php 

namespace app\admin\controller;
use think\exception\ValidateException;
use app\model\UsersRoles;
use think\facade\Db;

class UsersrolesController extends Base {

	function index(){
		$keyword = trim(input('post.keyword', '', 'serach_in'));
		$status = trim(input('post.status', '', 'serach_in'));

		$where = [];
		if ($status !== '') {
			$where['status'] = $status;
		}

		$field = 'id,title,status,description';
		$query = UsersRoles::where($where);

		if (!empty($keyword)) {
			$query->where('title', 'like', '%' . $keyword . '%');
		}

		$res = $query->field($field)->order('id desc')->paginate(getpage())->toArray();

		$data['data'] = $res;
		return $this->json($data);
	}

	function updateExt(){
		$postField = 'id,status';
		$data = $this->request->only(explode(',',$postField),'post',null);
		if(!$data['id']) throw new ValidateException ('参数错误');
		UsersRoles::update($data);
		return $this->json(['msg'=>'操作成功']);
	}

	public function add(){
		$postField = 'title,status,description,access';
		$data = $this->request->only(explode(',',$postField),'post',null);

		$this->validate($data,\app\validate\UsersRoles::class);
		
		if(!in_array('Home',$data['access'])){
			array_push($data['access'],'Home');
		}
		
		$data['access'] = implode(',',$data['access']);

		$res = UsersRoles::create($data);
		return $this->json(['msg'=>'添加成功','data'=>$res->id]);
	}

	public function update(){

		$id = $this->request->post('id');
		if (empty($id)) {
			return $this->add();
		} else {
			$postField = 'id,title,status,description,access';
			$data = $this->request->only(explode(',',$postField),'post',null);
	
			$this->validate($data,\app\validate\UsersRoles::class);
			
			if(!in_array('Home',$data['access'])){
				array_push($data['access'],'Home');
			}
			
			$data['access'] = implode(',',$data['access']);
	
			UsersRoles::update($data);
			return $this->json(['msg'=>'修改成功']);
		}
		
	}
	
	function getUpdateInfo(){
		$id =  $this->request->post('id', '', 'serach_in');
		if(!$id) $this->error('参数错误');
		$field = 'id,title,status,description,access';
		$res = UsersRoles::field($field)->find($id);
		$res['access'] = explode(',',$res['access']);
		return $this->json(['data'=>$res]);
	}

	function delete(){
		$idx =  $this->request->post('id', '', 'serach_in');
		if(!$idx) throw new ValidateException ('参数错误');
		if(in_array(1,explode(',',$idx))){
			$this->error('超级管理员分组禁止删除');
		}
		UsersRoles::destroy(['id'=>explode(',',$idx)],true);
		return $this->json(['msg'=>'操作成功']);
	}
}